import { DirectiveBinding } from 'vue'
import useUserStore from '@/stores/user'

export default {
  /**
   * 权限指令
   * @param el DOM元素
   * @param binding 绑定对象
   */
  permission(el: HTMLElement, binding: DirectiveBinding) {
    const { value } = binding
    const data = {
      id: undefined,
      name: undefined,
    }

    if (typeof value === 'string') {
      data.name = value
    } else {
      data.id = value.id
      data.name = value.name
    }

    const userStore = useUserStore()
    if (userStore.isAdmin) {
      return
    }

    const ids = userStore.getAllPermissionId(data.name)
    if (
      (data.id === undefined && ids.length === 0) ||
      (data.id !== undefined && !ids.includes('' + data.id))
    ) {
      el.remove()
    }
  },
}
